package com.ruoyi.cms.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.Collections;

/**
 * CMS模块Swagger配置
 *
 * @author houyong
 */
@Configuration
public class SwaggerConfig {

    /**
     * 管理端API分组
     */
    @Bean
    public GroupedOpenApi managerApi() {
        return GroupedOpenApi.builder()
                .group("cms-manager")
                .pathsToMatch("/cms/manager/**")
                .build();
    }

    /**
     * 网站端API分组
     */
    @Bean
    public GroupedOpenApi websiteApi() {
        return GroupedOpenApi.builder()
                .group("cms-website")
                .pathsToMatch("/cms/website/**")
                .build();
    }

    @Value("${springdoc.gatewayUrl}")
    private String gatewayUrl;

    /**
     * CMS API信息配置
     */
    @Bean
    public OpenAPI cmsOpenAPI() {
        Server server = new Server()
                .url(gatewayUrl)
                .description("CMS内容管理系统接口文档");

        return new OpenAPI()
                .addServersItem(server)
                .info(new Info()
                        .title("CMS内容管理系统API")
                        .description("CMS内容管理系统接口文档")
                        .version("v1.0"))
                .components(new Components()
                        .addSecuritySchemes("Authorization",
                                new SecurityScheme()
                                        .type(SecurityScheme.Type.HTTP)
                        ))
                .addSecurityItem(new SecurityRequirement().addList("Authorization"));
    }

    /**
     * 为CMS模块配置跨域支持，增强生产环境Swagger的兼容性
     */
    @Bean
    public CorsWebFilter cmsCorsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/cms/**", config);
        source.registerCorsConfiguration("/v3/api-docs/**", config);

        return new CorsWebFilter(source);
    }
}